package file;

import ipconfig.Ipconfig;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import main.ClientThread;
import main.Main;
import voSetting.PortVO;
import voSetting.StateSetVO;
import chat.Chatting;
import custom.tree.EmployeesSearch;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.border.TitledBorder;

public class FileTransfer extends JFrame {
	boolean maximum = false;
	Point point = new Point();  
	boolean resizing = false; 
	
	Ipconfig ip = new Ipconfig();
	
	final int FILE_UPLOAD = 1;
	final int FILE_DOWNLOAD = 2;
	
	private FileServer fileServer = null;
	private FileClientThread fileClientThread = null;
	private String filepath;
	private String filename;
	private long filesize;
	private int order = 0;
	private int b = 10;
	private int number = 0;
	private int deleteCount = 0;
	
	Vector<FileTransferPanel> vectorFileTransferPanels = new Vector<FileTransferPanel>();
	Vector<String> v_filer = new Vector<String>();
	
	EmployeesSearch em_f = null;
	FileTransferPanel fup = null;
	
	int portNumber;
	Chatting chat = null;
	
	Main main = null;
	
	//파일 정보를 담은 VO객체를 생성합니다.
	FileInfoVO fileInfoVO = null;
	//파일 VO객체를 담는 백터를 생성 및 초기화 합니다.
	Vector<FileInfoVO> vector_fileInfo = new Vector<FileInfoVO>();
	//클라이언트 저장
	HashMap<String, FileServerThread> client = new HashMap<String, FileServerThread>();
	
	PortVO portVO = null;
	
	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JPanel panel_2;
	private JPanel panel_3;
	private JPanel panel_4;
	private JButton btn_file;
	private JButton btn_Transfer;
	private JButton btn_DeleteAll;
	private JScrollPane scrollPane;
	protected JPanel panel_5;
	private JLabel label;
	public JLabel lb_name_to;
	private JPanel panel_7;
	private JButton btn_Search;
	private JPanel panel_8;
	private JPanel panel_9;
	private JButton button;
	private JButton button_1;
	private JButton button_2;
	private JLabel lblNewLabel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					FileTransfer frame = new FileTransfer();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public FileTransfer() {
		setUndecorated(true);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 420, 320);
		setMinimumSize(new Dimension(420, 320));
		contentPane = new JPanel();
		contentPane.setBorder(null);
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.CENTER);
		contentPane.add(getPanel_8(), BorderLayout.NORTH);
		addMouseListener(new MouseAdapter() {  
		      public void mousePressed(MouseEvent e) {  
		        resizing = getCursor().equals(Cursor.getDefaultCursor())? false:true;  
		        if(!e.isMetaDown()){  
		          point.x = e.getX();  
		          point.y = e.getY();  
		        }  
		      }  
		    });  
		addMouseMotionListener(new MouseMotionAdapter() {  
		      public void mouseDragged(MouseEvent e) {  
		        if(resizing){  
		          Point pt = e.getPoint(); 
		          setSize(getWidth()+pt.x - point.x, getHeight()+pt.y-point.y);  
		          point.x = pt.x;  
		          point.y = pt.y;
		        }  
		        else if(!e.isMetaDown()){  
		        Point p = getLocation();  
		        setLocation(p.x + e.getX() - point.x,  
		            p.y + e.getY() - point.y);  
		        }  
		      }  
		      public void mouseMoved(MouseEvent me){  
		        Point cursorLocation = me.getPoint();  
		        int xPos = cursorLocation.x;  
		        int yPos = cursorLocation.y;  
		        if(xPos < 5) setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));  
		        else if(xPos > getContentPane().getWidth()-5) setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));  
		        else if(yPos < 5) setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));  
		        else if(yPos > getContentPane().getHeight()-5) setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));  
		        else if(getCursor().equals(Cursor.getDefaultCursor()) == false) setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));  
		      }  
		    });
	}
	
	public FileTransfer(Main main) {
		
		this.main = main;
		
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 420, 320);
		setMinimumSize(new Dimension(420, 320));
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.CENTER);
		
		addMouseListener(new MouseAdapter() {  
		      public void mousePressed(MouseEvent e) {  
		        resizing = getCursor().equals(Cursor.getDefaultCursor())? false:true;  
		        if(!e.isMetaDown()){  
		          point.x = e.getX();  
		          point.y = e.getY();  
		        }  
		      }  
		    });  
		addMouseMotionListener(new MouseMotionAdapter() {  
			  public void mouseDragged(MouseEvent e) {  
			    if(resizing){  
			      Point pt = e.getPoint(); 
			      setSize(getWidth()+pt.x - point.x, getHeight()+pt.y-point.y);  
			      point.x = pt.x;  
			      point.y = pt.y;
			    }  
			    else if(!e.isMetaDown()){  
			    Point p = getLocation();  
			    setLocation(p.x + e.getX() - point.x,  
			        p.y + e.getY() - point.y);  
			    }  
			  }  
			  public void mouseMoved(MouseEvent me){  
			    Point cursorLocation = me.getPoint();  
			    int xPos = cursorLocation.x;  
			    int yPos = cursorLocation.y;  
			    if(xPos < 5) setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));  
			    else if(xPos > getContentPane().getWidth()-5) setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));  
			    else if(yPos < 5) setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));  
			    else if(yPos > getContentPane().getHeight()-5) setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));  
			    else if(getCursor().equals(Cursor.getDefaultCursor()) == false) setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));  
			  }  
	    });
	}
	
	public void setV_filer(Vector<String> v){
		
		this.v_filer = v;
		System.out.println("setV_filer 에서 값을 찍습니다. 보낼 사람들");
		for(int i = 0; i < v_filer.size(); i++){
			System.out.println( v_filer.get(i));
		}
	}
	
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getPanel_2(), BorderLayout.SOUTH);
			panel.add(getPanel_3(), BorderLayout.CENTER);
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getPanel_4(), BorderLayout.SOUTH);
		}
		return panel_1;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.setBackground(new Color(152,191,218));
			panel_2.setBorder(new EmptyBorder(5, 5, 5, 5));
			panel_2.setLayout(new BorderLayout(0, 0));
			panel_2.add(getBtn_Transfer(), BorderLayout.EAST);
			panel_2.add(getBtn_DeleteAll(), BorderLayout.WEST);
		}
		return panel_2;
	}
	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setBackground(new Color(255, 255, 255));
			panel_3.setBorder(new EmptyBorder(5, 5, 5, 5));
			panel_3.setLayout(new BorderLayout(0, 0));
			panel_3.add(getScrollPane(), BorderLayout.CENTER);
		}
		return panel_3;
	}
	private JPanel getPanel_4() {
		if (panel_4 == null) {
			panel_4 = new JPanel();
			panel_4.setBackground(new Color(152,191,218));
			panel_4.setLayout(new BorderLayout(0, 0));
			panel_4.add(getLabel(), BorderLayout.WEST);
			panel_4.add(getLb_name_to(), BorderLayout.CENTER);
			panel_4.add(getPanel_7(), BorderLayout.EAST);
		}
		return panel_4;
	}
	private JButton getBtn_file() {
		if (btn_file == null) {
			btn_file = new JButton("파일 선택");
			btn_file.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			btn_file.setBackground(new Color(152,191,218));
			btn_file.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					JFileChooser jc = new JFileChooser();	
					int yn = jc.showOpenDialog(FileTransfer.this);	
					if(yn == JFileChooser.APPROVE_OPTION){	
						
						 if(number < 4){
							fup = new FileTransferPanel();
							fup.setFup(FileTransfer.this);
							fup.setToolTipText(String.valueOf(order));
							
							fup.setBounds(10, (b), 380, 45);
							b += 45;
							
							fup.setVisible(true);
							
							panel_5.add(fup);
							panel_5.updateUI();							
							
							filepath = jc.getSelectedFile().getPath();	
							filename = jc.getSelectedFile().getName();
							File f = new File(filepath);										
							filesize = f.length();	
												
							fup.label_fileName.setText(filename);
							fup.setAddId(filepath, filename);
							number++;
							order++;
							vectorFileTransferPanels.add(fup);
							
							//파일 정보를 담은 VO객체에 값을 넣어서 백터에 저장합니다.
							fileInfoVO = new FileInfoVO(filename, filepath, filesize);
							vector_fileInfo.add(fileInfoVO);
							
							labelNameRedefine();
						 }else{
							 JOptionPane.showMessageDialog(FileTransfer.this,"파일전송은 4개까지만 가능합니다.");					 
						 }					
					}
					System.out.println("선택된 파일의 경로: "+filepath);
					System.out.println("선택된 파일의 이름: "+filename);
					
					System.out.println("파일 정보를 담은 Vector의 file_info에 저장된 fileSendUser: "+main.getClientThread().getSmvo().getM_id());
					for(int i=0; i<vector_fileInfo.size(); i++){
						System.out.println("파일 정보를 담은 Vector의 file_info에 저장된 fileName: "+vector_fileInfo.get(i).getFileName());
						System.out.println("파일 정보를 담은 Vector의 file_info에 저장된 filePath: "+vector_fileInfo.get(i).getFilePath());
						System.out.println("파일 정보를 담은 Vector의 file_info에 저장된 fileSize: "+vector_fileInfo.get(i).getFileSize()+"Bytes");
						for(int j=0; j<v_filer.size(); j++){
							System.out.println("파일 정보를 담은 Vector의 file_info에 저장된 fileReceiveUser: "+v_filer.get(j));
						}
					}
				}
			});
			btn_file.setFont(new Font("맑은 고딕", Font.BOLD, 12));
		}
		return btn_file;
	}
	private JButton getBtn_Transfer() {
		if (btn_Transfer == null) {
			btn_Transfer = new JButton("파일 전송");
			btn_Transfer.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			btn_Transfer.setBackground(new Color(152,191,218));
			btn_Transfer.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					
					System.out.println("파일전송 클릭!");
					int select = JOptionPane.showConfirmDialog(FileTransfer.this, "파일 업로드를 실행 하시겠습니까?", "파일 업로드", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
					
					if(select == 0){
						//선택된 유저에게 파일을 전송 하기 위한 로직 입니다.
						StateSetVO ssvo = new StateSetVO();
						ssvo.setVo_type(2);
						portVO = new PortVO();
						portVO.setM_id(main.getClientThread().getSmvo().getM_id());
						portVO.setCommand(2);
						
						System.out.println("파일 전송에서 받을 사람을 찍습니다.");
						for(int i = 0; i < v_filer.size(); i++){
							System.out.println("받을 사람 아이디  : " + v_filer.get(i));
						}
						portVO.setInvitation_user_list(v_filer);
						
						System.out.println("값이 잘 들어갔는지 찍습니다.");
						for(int i = 0; i < portVO.getInvitation_user_list().size(); i++){
							System.out.println("pvo.getInvitation_user_list() value : " + portVO.getInvitation_user_list().get(i));
						}
						System.out.println("값을 vo에 셋팅합니다.");
						ssvo.setVo(portVO);
						
						try {
							System.out.println("값을 보내기 시작합니다. (파일 트렌스퍼)");
							main.getClientThread().getOos().writeObject(ssvo);
							System.out.println("값 보내기를 완료합니다(파일 트렌스퍼)");
							main.getClientThread().getOos().flush();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}else {
						JOptionPane.showMessageDialog(FileTransfer.this, "파일 업로드를 취소 하셨습니다.");
					}
				}
			});
			btn_Transfer.setFont(new Font("맑은 고딕", Font.BOLD, 12));
		}
		return btn_Transfer;
	}
	
	public void start_upload(){
		
		System.out.println("start_upload실행");
		System.out.println("업로드를 시작합니다");
		
		//파일 서버에 접속을 시도합니다.
		Socket socket;
		
		try {
			System.out.println("업로드 소켓 연결을 시작합니다");
			socket = new Socket(ip.getFIXED_IP(), getPortNumber());
			System.out.println("업로드 소켓이 서버소켓에 연결되었습니다.");
			System.out.println("파일 클라이언트 스레드 생성전");
			System.out.println("소켓정보: "+socket);
			System.out.println("파일경로: "+filepath);
			System.out.println("파일 패널: "+vectorFileTransferPanels);
			fileClientThread =  new FileClientThread(socket, vector_fileInfo, portVO.getM_id(), v_filer, FILE_UPLOAD, vectorFileTransferPanels, FileTransfer.this);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void start_download(){
		
		System.out.println("start_download실행");
		System.out.println("다운로드를 시작합니다");
		//파일 서버에 접속을 시도합니다.
		Socket socket;
	
		try {
			System.out.println("다운로드 소켓 연결을 시작합니다");
			socket = new Socket(ip.getFIXED_IP(), getPortNumber());
			System.out.println("다운로드 소켓이 서버소켓에 연결되었습니다.");
			System.out.println("파일 클라이언트 스레드 생성전");
			System.out.println("소켓정보: "+socket);
			System.out.println("파일 패널: "+vectorFileTransferPanels);
			fileClientThread = new FileClientThread(socket, vector_fileInfo, portVO.getM_id(), v_filer , FILE_DOWNLOAD, vectorFileTransferPanels, this);
			fileClientThread.setPortNumer(getPortNumber());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private JButton getBtn_DeleteAll() {
		if (btn_DeleteAll == null) {
			btn_DeleteAll = new JButton("전체 삭제");
			btn_DeleteAll.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			btn_DeleteAll.setBackground(new Color(152,191,218));
			btn_DeleteAll.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					
					Iterator<FileTransferPanel> iter2 = vectorFileTransferPanels.iterator();
					
					while(iter2.hasNext()){
						FileTransferPanel setMap =  iter2.next();
						setMap.setVisible(false);
					}
					vectorFileTransferPanels.clear();
					b = 10;			
					number = 0;
					order = 0;
					panel_5.updateUI();
				}
			});
			btn_DeleteAll.setFont(new Font("맑은 고딕", Font.BOLD, 12));
		}
		return btn_DeleteAll;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getPanel_5());
		}
		return scrollPane;
	}
	private JPanel getPanel_5() {
		if (panel_5 == null) {
			panel_5 = new JPanel();
			panel_5.setBackground(new Color(255, 255, 255));
			panel_5.setLayout(null);
		}
		return panel_5;
	}

	public void setChat(Chatting chatting) {
		this.chat = chatting;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("받는 사람");
			label.setFont(new Font("맑은 고딕", Font.BOLD, 12));
		}
		return label;
	}
	private JLabel getLb_name_to() {
		if (lb_name_to == null) {
			lb_name_to = new JLabel("받으실 분을 선택해주세요.");
			lb_name_to.setHorizontalAlignment(SwingConstants.CENTER);
			lb_name_to.setFont(new Font("맑은 고딕", Font.PLAIN, 12));
		}
		return lb_name_to;
	}
	private JPanel getPanel_7() {
		if (panel_7 == null) {
			panel_7 = new JPanel();
			panel_7.setLayout(new GridLayout(1, 2, 0, 0));
			panel_7.add(getBtn_Search());
			panel_7.add(getBtn_file());
		}
		return panel_7;
	}
	private JButton getBtn_Search() {
		if (btn_Search == null) {
			btn_Search = new JButton("직원 찾기 ");
			btn_Search.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			btn_Search.setBackground(new Color(152,191,218));
			btn_Search.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					em_f = new EmployeesSearch();
					em_f.addEmployeeFrame(3, FileTransfer.this);
					em_f.setVisible(true);		
				}
			});
			btn_Search.setToolTipText("새로 파일을 보낼 분을 선택해주세요.");
			btn_Search.setFont(new Font("맑은 고딕", Font.BOLD, 12));
		}
		return btn_Search;
	}
	
	public void labelNameRedefine() {
		
		for(int i=0; i<getVec().size(); i++){
			getVec().get(i).label_file.setText("파일"+(i+1)+"  ");
		}
	}
	
	public String getFilename() {
		return filename;
	}
	
	public void setFilename(String filename) {
		this.filename = filename;
	}
	
	public int getB() {
		return b;
	}
	
	public void setB(int b) {
		this.b = b;
	}
	
	public int getOrder() {
		return order;
	}
	
	public void setOrder(int order) {
		this.order = order;
	}
	
	public int getNumber() {
		return number;
	}
	
	public void setNumber(int number) {
		this.number = number;
	}
	
	public Vector<FileTransferPanel> getVec() {
		return vectorFileTransferPanels;
	}
	
	public void setVec(Vector<FileTransferPanel> vectorFileTransferPanels) {
		this.vectorFileTransferPanels = vectorFileTransferPanels;
	}

	public int getPortNumber() {
		return portNumber;
	}
	
	public void setPortNumber(int portNumber) {
		this.portNumber = portNumber;
	}
	
	public Vector<String> getV_filer() {
		return v_filer;
	}
	
	public PortVO getPortVO() {
		return portVO;
	}
	
	public void setPortVO(PortVO portVO) {
		this.portVO = portVO;
	}
	private JPanel getPanel_8() {
		if (panel_8 == null) {
			panel_8 = new JPanel();
			panel_8.setBackground(new Color(152,191,218));
			panel_8.setBorder(new EmptyBorder(5, 5, 5, 6));
			panel_8.setLayout(new BorderLayout(0, 0));
			panel_8.add(getPanel_9(), BorderLayout.EAST);
			panel_8.add(getPanel_1(), BorderLayout.SOUTH);
			panel_8.add(getLblNewLabel(), BorderLayout.WEST);
		}
		return panel_8;
	}
	private JPanel getPanel_9() {
		if (panel_9 == null) {
			panel_9 = new JPanel();
			panel_9.setBackground(new Color(152,191,218));
			panel_9.add(getButton());
			panel_9.add(getButton_1());
			panel_9.add(getButton_2());
		}
		return panel_9;
	}
	private JButton getButton() {
		if (button == null) {
			button = new JButton("");
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					setState(JFrame.ICONIFIED);	
				}
			});
			button.setIcon(new ImageIcon("C:\\Program Files\\Mino Corp\\system\\minimum.png"));
			button.setBorder(null);
			button.setBackground(new Color(152,191,218));
		}
		return button;
	}
	private JButton getButton_1() {
		if (button_1 == null) {
			button_1 = new JButton("");
			button_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(maximum !=true){
						setExtendedState(JFrame.MAXIMIZED_BOTH);	
						button_1.setIcon(new ImageIcon("C:\\Program Files\\Mino Corp\\system\\initsize.png"));
						maximum = true;
					}else{
						setBounds(100, 100, 420, 320);
						button_1.setIcon(new ImageIcon("C:\\Program Files\\Mino Corp\\system\\maximum.png"));
						maximum = false;
					}
				}
			});
			button_1.setIcon(new ImageIcon("C:\\Program Files\\Mino Corp\\system\\maximum.png"));
			button_1.setBorder(null);
			button_1.setBackground(new Color(152,191,218));
		}
		return button_1;
	}
	private JButton getButton_2() {
		if (button_2 == null) {
			button_2 = new JButton("");
			button_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					dispose();
				}
			});
			button_2.setIcon(new ImageIcon("C:\\Program Files\\Mino Corp\\system\\close.png"));
			button_2.setBorder(null);
			button_2.setBackground(new Color(152,191,218));
		}
		return button_2;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("FILE TRANSFER");
			lblNewLabel.setForeground(Color.WHITE);
			lblNewLabel.setFont(new Font("맑은 고딕", Font.BOLD | Font.ITALIC, 12));
		}
		return lblNewLabel;
	}
}
